import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_network/src/network/http_manager.dart';
import 'package:path_provider/path_provider.dart';

class Download {
  
  static Future<DownloadResponse> file({
    required String url,
    String? path,
    ProgressCallback? progress,
    CancelToken? cancelToken,
  }) async {
    Dio dio = Http.dio;
    String? savePath = path;
    Response response;
    if (savePath == null) {
      if (Platform.isIOS) {
        savePath = (await getApplicationDocumentsDirectory()).path;
      } else {
        savePath = (await getApplicationSupportDirectory()).path;
      }
      savePath += "/download";
    }
    try {
      response = await dio.download(
        url,
        savePath,
        cancelToken: cancelToken,
        onReceiveProgress: progress,
      );
      if (response.statusCode == 200) {
        return DownloadResponse()
          ..isSuccess = true
          ..response = response
          ..msg = "下载成功"
          ..path = path;
      } else {
        return DownloadResponse()
          ..isSuccess = false
          ..response = response
          ..msg = "下载失败"
          ..path = path;
        // throw Exception('接口出错');
      }
    } on DioError catch (e) {
      return DownloadResponse()
        ..isSuccess = false
        ..msg = e.type == DioErrorType.cancel ? "已取消下载！" : '下载出错，请检查网络连接！'
        ..path = path;
    }
  }
}

class DownloadResponse {
  bool? isSuccess;
  String? path;
  Response? response;
  String? msg;
}
